package com.nuanshui.heatedloan.middleware.whatchat.util;

import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.springContext.SpringContextUtil;
import com.nuanshui.framework.springContext.SpringPropertiesUtil;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.framework.utils.redis.JedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weixin.popular.api.SnsAPI;
import weixin.popular.api.TokenAPI;
import weixin.popular.api.UserAPI;
import weixin.popular.bean.sns.SnsToken;
import weixin.popular.bean.token.Token;
import weixin.popular.bean.user.User;

/**
 * @author zss
 * @date 2017/6/9
 * @description 微信公众平台工具开发工具
 */
public class WechatPPUtil {

    private static final Logger logger = LoggerFactory.getLogger(WechatPPUtil.class);

    /**
     * 获取appid
     * @return
     */
    public static String getAppid() {
        return SpringPropertiesUtil.getPropertiestValue("wechat.appid");
    }

    /**
     * 获取secret
     * @return
     */
    public static String getAppsecret() {
        return SpringPropertiesUtil.getPropertiestValue("wechat.appsecret");
    }

    /**
     * 通过appid和secret来获取Token对象
     * @return
     */
    public static String getAccessToken(){
        JedisUtil jedisUtil = (JedisUtil) SpringContextUtil.getBean(JedisUtil.class);
        String accessToken = jedisUtil.get("WECHAT_ACCESS_KEY");
        SpringPropertiesUtil.getPropertiestValue("env");
        if(SysStringUtils.isEmpty(accessToken)) {
            Token token=TokenAPI.token(getAppid(),getAppsecret());
            if (token !=null){
                String s= token.getAccess_token();
                accessToken=s;
                jedisUtil.set("WECHAT_ACCESS_KEY", s);
                jedisUtil.expire("WECHAT_ACCESS_KEY", 3600);
            }
            LogUtil.info(logger, "accessToken=" + accessToken);
        }
        return accessToken;
    }

    /**
     *
     * @param code
     * @return
     */
    public static SnsToken getSnsToken(String code){
        SnsToken snsToken= SnsAPI.oauth2AccessToken(getAppid(),getAppsecret(),code);
        return snsToken;
    }

    /**
     *通过openId来获取User对象对应的字符串
     * @param openId
     * @return
     */
    public static String getStrByOpenId(String openId){
        String access_token=getAccessToken();
        User user= UserAPI.userInfo(access_token,openId);
        //将对象转为字符串
        String result= JSON.toJSONString(user);
        return result;
    }

    /**
     * 通过code来获取User对象对应的字符串
     * @param code
     * @return
     */
     public static String getStrByCode(String code){
        SnsToken snsToken =getSnsToken(code);
        if (snsToken !=null){
           return getStrByOpenId(snsToken.getOpenid());
        }
        return "";
     }
}

